package pj.pamper.clw;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.MimeTypeMap;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.example.framelib.entity.VersionEntity;
import com.example.framelib.mvp.frame.MvpActivity;
import com.example.framelib.mvp.frame.base.BaseView;
import com.example.framelib.observable.CustomObserver;
import com.example.framelib.observable.ObservableHelper;
import com.example.framelib.receiver.NetworkBroadcastReceiver;
import com.example.framelib.ui.activity.BaseActivity;
import com.example.framelib.ui.view.CustomAlertDialog;
import com.example.framelib.ui.view.NumberProgressDialog;
import com.example.framelib.utils.ActivityManagerUtil;
import com.example.framelib.utils.EventCenter;
import com.example.framelib.utils.FileUtil;
import com.example.framelib.utils.NetworkUtils;
import com.example.framelib.utils.VersionUtil;
import com.google.zxing.CaptureActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pj.pamper.clw.Utils.PathUtils;
import pj.pamper.clw.mvp.contract.MainContract;
import pj.pamper.clw.mvp.presenter.MainPresenter;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import zlc.season.rxdownload2.RxDownload;
import zlc.season.rxdownload2.entity.DownloadStatus;

public class MainActivity extends MvpActivity<MainPresenter> implements MainContract.View, BaseActivity.RequestPermission, CustomObserver {
    @BindView(R.id.webView)
    protected WebView webView;

    private final  String TAG = getClass().getSimpleName();

    private MediaRecorder recorder;
    private MediaPlayer player;
    private String voicePath;
    private long time;

    protected String[] videoPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
    };

    private String[] lackPermissions;

    private static final int PERMISSION_REQUEST_CODE = 0;
    private static final int SCAN_REQUEST_CODE = 1;
    private static final int PERMSIION_SCAN_CODE = 1;
    private static final int VERSION_REQUEST_CODE = 3;

    List<String> filePath = new ArrayList<>();//最终选择的图片地址

    private String currentUrl = "";//webview缓存的原因，shouldOverrideUrlLoading不会记录浏览过的页面
    private String hisUrl = "";

    private NetworkBroadcastReceiver networkBroadcastReceiver;

    private boolean isFirst = true; //网络状态第一次连接判断

    private boolean isHaveNet;

    private static final String APP_CACAHE_DIRNAME = "/webcache";

    private int maxSelectNum = 3;
    private List<LocalMedia> selectList = new ArrayList<>();
    private String paths = "";

    private long mExitTime = 0;



    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void initView() {
        isHaveNet = NetworkUtils.isAvailable(this);

        currentUrl = "http://221.229.221.39:5008/H5/html/login/login.html";
        ObservableHelper.addObserver(this, ObservableHelper.REGISTER_NETWORK_STATE_CHANGE);
        registReceiver();

        webView.setVerticalScrollbarOverlay(true);
        initWebView();

        String url = "http://221.229.221.39:5008/H5/html/login/login.html";
        //String url = "file:///android_asset/test.html";
        //在js中调用本地java方法
        webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView");

        webView.setWebViewClient(new myWebClient());

        //添加客户端支持
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                result.confirm();
                return true;
            }
        });

        webView.loadUrl(url);

        player = new MediaPlayer();

        setRequestPermissionListener(this);


    }

    private void initWebView() {
        //设置WebView支持JavaScript
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setJavaScriptEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
        // 开启 DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        //开启 database storage API 功能
        webSettings.setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        //      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
        Log.e(TAG, "cacheDirPath=" + cacheDirPath);
        //设置数据库缓存路径
        webSettings.setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
        webSettings.setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        webSettings.setAppCacheEnabled(true);
        //自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setLoadWithOverviewMode(true);

        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_main;
    }

    @Override
    public boolean isApplyEventBus() {
        return false;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {

    }

    @Override
    public void onRequestResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (checkPermissions(lackPermissions)) {
                fasong();
            } else {
                Toast.makeText(this, "您拒绝了相关权限，该功能无法使用！", Toast.LENGTH_SHORT).show();
            }
        }


        if(requestCode == PERMSIION_SCAN_CODE){
            if(checkPermissions(lackPermissions)){
                toScan();
            }else{
                Toast.makeText(this, "您拒绝了相关权限，该功能无法使用！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void showError(String errorMsg) {
        replyToJs(0);
    }

    @Override
    public void showSuccess() {
        replyToJs(1);
        PictureFileUtils.deleteCacheDirFile(this);
    }

    @Override
    public void showVersion(final VersionEntity version) {
        if (checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            VersionUtil.getInstance().initFile("dirDownload" , "clw" , version , this);
            VersionUtil.getInstance().downloadApk();
        } else {
            requestSystemPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, VERSION_REQUEST_CODE);
        }
    }

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    /**
     * 网络变化处理
     */
    @Override
    public void update(Object data, int type) {
        if ((int) data == NetworkBroadcastReceiver.HAVE_NO_NETWORK) {
            if (isFirst) {
                isFirst = false;
            }
            try {
                new Thread().sleep(500);
                if (!NetworkUtils.isAvailable(this)) {
                    isHaveNet = false;
                    webView.loadUrl("file:///android_asset/error.html");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } else {
            if (isFirst) {
                isFirst = false;
            } else {
                if (!isHaveNet) {
                    isHaveNet = true;
                    webView.loadUrl(currentUrl);
                }
            }
        }
    }

    /**
     * 在js中调用java代码
     */
    private class JsInterface {
        private Context mContext;

        public JsInterface(Context context) {
            this.mContext = context;
        }

        @JavascriptInterface
        public void startRecording() {
            lackPermissions = checkLackPermissions(videoPermissions);
            if (lackPermissions != null && lackPermissions.length > 0) {
                requestSystemPermissions(lackPermissions, PERMISSION_REQUEST_CODE);
            } else {
                fasong();
            }
        }

        @JavascriptInterface
        public void stopRecording() {
            jieshu();
        }

        @JavascriptInterface
        public void playRecording() {
            play();
        }

        @JavascriptInterface
        public void openNet() {
            startActivity(new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS));
        }

        @JavascriptInterface
        public void reload() {
            webView.loadUrl(currentUrl);
        }

        @JavascriptInterface
        public void checkVersion(){
            mPresenter.checkVersion();
        }

        @JavascriptInterface
        public void imagePicker(int count) {
            paths = "";
            maxSelectNum = count;
            imagePick();
        }

        @JavascriptInterface
        public void scan(){
            //本地Zxing库没有对6.0权限做处理，此处添加
            lackPermissions = checkLackPermissions(new String[]{Manifest.permission.CAMERA});
            if (lackPermissions != null && lackPermissions.length > 0) {
                requestSystemPermissions(lackPermissions, PERMSIION_SCAN_CODE);
            } else {
                toScan();
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @JavascriptInterface
        public void sendForm(final String reportType, final String reportDesc, final String tel) {
            if (filePath == null || filePath.size() == 0) {
                mPresenter.add(reportType, null, reportDesc, TextUtils.isEmpty(voicePath) ? null : new File(voicePath), tel);
                return;
            }

            Luban.get(MainActivity.this)
                    .loadFiles(filePath)
                    .putGear(Luban.THIRD_GEAR)
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess(File file) {
                        }

                        @Override
                        public void onSuccess(List<File> files) {
                            if (TextUtils.isEmpty(voicePath)) {
                                mPresenter.add(reportType, files, reportDesc, null, tel);
                            } else {
                                mPresenter.add(reportType, files, reportDesc, new File(voicePath), tel);
                            }

                        }

                        @Override
                        public void onError(Throwable e) {
                            replyToJs(2);
                        }
                    }).compress();


        }

        @JavascriptInterface
        public void deletePic(int index) {
            filePath.remove(index);
        }
    }

    /**
     * 在java中调用js代码
     */
    public void replyToJs(int type) {
        //0 请求失败 1请求成功 2 图片压缩失败
        webView.loadUrl("javascript:showInfoFromJava('" + type + "')");
    }

    public void toScan(){
        Intent openCameraIntent = new Intent(MainActivity.this, CaptureActivity.class);
        startActivityForResult(openCameraIntent, SCAN_REQUEST_CODE);
    }

    /**
     * 开始录音
     */
    private void fasong() {
        Log.e(TAG , "开始录音");
        if (recorder != null) {
            //不等于空的时候让他变闲置
            recorder.reset();
        } else {
            recorder = new MediaRecorder();
        }
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        //输出格式
        recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
        //设置音频编码器
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        //缓存目录
        String str = FileUtil.getSDCardPath() + "/clw/video/";
        //检查该目录是否存在  否则创建
        FileUtil.checkDir(str);
        //设置文件名
        voicePath = str + System.currentTimeMillis() + ".amr";
        ///storage/emulated/0//clw/video/1543976531567.amr
        //设置录音的输出路径
        recorder.setOutputFile(voicePath);

        try {
            recorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        recorder.start();
        time = System.currentTimeMillis();
    }

    /**
     * 结束语音
     */
    private void jieshu() {
        Log.e(TAG, "结束语音");
        recorder.stop();
        long shijian = System.currentTimeMillis() - time;
//        if (shijian < 1000) {//判断，如果录音时间小于一秒，则删除文件提示，过短
//            File file = new File(voicePath);
//            if (file.exists()) {//判断文件是否存在，如果存在删除文件
//                file.delete();//删除文件
//                Toast.makeText(MainActivity.this, "录音时间过短", Toast.LENGTH_SHORT).show();
//            }
//        }
        //重置
        recorder.release();
        if (recorder != null) {
            recorder.release();
            recorder = null;
            System.gc();
        }
    }

    /**
     * 播放录音
     */
    private void play() {
        Log.e(TAG, "播放录音");
        if (player != null) {
            player.reset();
            try {
                //设置语言的来源
                player.setDataSource(voicePath);
                //初始化
                player.prepare();
                //开始播放
                player.start();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片选择结果回调
                selectList = PictureSelector.obtainMultipleResult(intent);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                for (LocalMedia localMedia : selectList) {
                    if (localMedia.isCompressed()) {
                        if (paths == "") {
                            filePath.add(localMedia.getCompressPath());
                            paths = PathUtils.getUri(MainActivity.this, localMedia.getCompressPath()).toString();
                        } else {
                            filePath.add(localMedia.getCompressPath());
                            paths += "|" + PathUtils.getUri(MainActivity.this, localMedia.getCompressPath()).toString();
                        }
                    } else {
                        if (paths == "") {
                            filePath.add(localMedia.getPath());
                            paths = PathUtils.getUri(MainActivity.this, localMedia.getPath()).toString();
                        } else {
                            filePath.add(localMedia.getPath());
                            paths += "|" + PathUtils.getUri(MainActivity.this, localMedia.getPath()).toString();
                        }
                    }
                }
                webView.loadUrl("javascript:showUrisFromJava('" + paths + "')");
                Log.e(TAG , paths);
            }

            if(requestCode == SCAN_REQUEST_CODE){
                Bundle bundle = intent.getExtras();
                String scanResult = bundle.getString("result");
                webView.loadUrl("javascript:showScanInfoFromJava('" + scanResult + "')");
            }

            if (requestCode == VERSION_REQUEST_CODE) {
                if (checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    VersionUtil.getInstance().downloadApk();
                } else {
                    Toast.makeText(this, "权限被拒绝，无法操作", Toast.LENGTH_SHORT).show();
                    VersionUtil.getInstance().init();
                }
            }


        }

    }


    public class myWebClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            hisUrl = url;
            Log.e(TAG , "hisUrl:" + hisUrl);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            currentUrl = request.getUrl().toString();
            Log.e(TAG , "currentUrl:" + currentUrl);
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }


    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 监听网络变化
     */
    private void registReceiver() {
        //实例化IntentFilter对象
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkBroadcastReceiver = new NetworkBroadcastReceiver();
        //注册广播接收
        registerReceiver(networkBroadcastReceiver, filter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(networkBroadcastReceiver);
        clearWebViewCache();
    }

    /**
     * Webview物理返回键控制
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (webView.canGoBack()) {
                if(hisUrl.endsWith("index.html")){
                    if (System.currentTimeMillis() - mExitTime > 2000) {
                        Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                        mExitTime = System.currentTimeMillis();
                    }else if(System.currentTimeMillis() - mExitTime < 300){
                        Log.e(TAG , "onBackPressed点击过快");
                    } else {
                        ActivityManagerUtil.create().finishActivity();
                    }
                }else{
                    webView.goBack();
                }
                return true;
            } else {
                ActivityManagerUtil.create().finishActivity();
                return true;
            }

        }
        return false;
    }


    /**
     * 清理Webview缓存数据库
     */
    public void clearWebViewCache() {
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //WebView 缓存文件
        File appCacheDir = new File(getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME);
        Log.e(TAG, "appCacheDir path=" + appCacheDir.getAbsolutePath());

        File webviewCacheDir = new File(getCacheDir().getAbsolutePath() + "/webviewCache");
        Log.e(TAG, "webviewCacheDir path=" + webviewCacheDir.getAbsolutePath());

        //删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        //删除webview 缓存 缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
    }

    /**
     * 递归删除 文件/文件夹
     */
    public void deleteFile(File file) {

        Log.i(TAG, "delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            Log.e(TAG, "delete file no exists " + file.getAbsolutePath());
        }
    }

    /**
     * 打开相册
     */
    private void imagePick() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(maxSelectNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                //.compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .compress(false)// 是否压缩
                //.compressMode(LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                //.glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .selectionMedia(selectList)// 是否传入已选图片
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

}
